package com.bang.concurrency.example.singleton;

import com.bang.concurrency.annotations.NotThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Auther: Bang
 * @Date: 2019/9/30 21:16
 * @Description: 单例模式 懒汉式
 */
@NotThreadSafe
@Slf4j
public class SingletonExample1 {

    // 私有化构造方法
    private SingletonExample1() {
    }

    private static SingletonExample1 instance = null;

    // 静态工程方法
    public static SingletonExample1 getInstance() {

        if (null == instance) {
//            try {
//                Thread.sleep(100);
//            } catch (Exception e) {
//
//            }
            instance = new SingletonExample1();
        }
        return instance;
    }

    public static void main(String[] args) {
        ExecutorService service = Executors.newCachedThreadPool();
        Set<SingletonExample1> set = new CopyOnWriteArraySet<>();
        for (int i = 0; i < 1000; i++) {
            service.execute(() -> {
                SingletonExample1 instance = SingletonExample1.getInstance();
                set.add(instance);
            });
        }
        service.shutdown();
        System.err.println(set.size());
    }
}
